﻿package rob.skin{
	import flash.display.BitmapData;
	import flash.display.Sprite;
	import flash.geom.Matrix;
	import rob.data.RGB;
	import rob.core.Ini;
	
	public class TextureSkin{
		private var _bmp:BitmapData, _w:Number;
		private var _tMat:Matrix, _sMat:Matrix;
		private var _aUV:Array, _aV:Array;
		private var _matName:String
		
		public function TextureSkin(matName:String,aUVCoord:Array,aVertex:Array):void{
			_matName = matName;
			_aUV = aUVCoord;
			_aV = aVertex;
			_setupTexturing();
		}
		
		public function beginFill(mc:Sprite):void{
			_textureUpdate();
			var rMat:Matrix = _concat(_tMat,_sMat);
			with(mc.graphics){
				beginBitmapFill(_bmp,rMat,true,true);
			}
		}
		
		private function _setupTexturing():void{
			// texturing
			var pic = Ini.getTextureByName(_matName);
			_w = pic.width;
		//trace(_w);
			_bmp = new BitmapData(_w,_w);
			_bmp.draw(pic);
			
			_tMat = new Matrix( (_aUV[1].u - _aUV[0].u),(_aUV[1].v - _aUV[0].v), 
								(_aUV[2].u - _aUV[0].u),(_aUV[2].v - _aUV[0].v), 
								_aUV[0].u * _w, _aUV[0].v * _w );
			_tMat.invert();
			_sMat = new Matrix();
		}
		
		private function _textureUpdate():void{
			_sMat.a = (_aV[1].sx - _aV[0].sx )/_w; 
			_sMat.b = (_aV[1].sy - _aV[0].sy)/_w;
			_sMat.c = (_aV[2].sx - _aV[0].sx)/_w;
			_sMat.d = (_aV[2].sy - _aV[0].sy)/_w; 
			_sMat.tx = _aV[0].sx;
			_sMat.ty = _aV[0].sy;
		}
		
		
		private function _concat(m1,m2):Matrix{	
			var r:Matrix = new Matrix();
			r.a = m1.a * m2.a;
			r.d = m1.d * m2.d;
			r.b = r.c = 0;
			r.ty = m1.ty * m2.d + m2.ty;
			r.tx = m1.tx * m2.a + m2.tx;
			if( m1.b != 0 || m1.c !=0 || m2.b != 0 || m2.c != 0 )
			{
				r.a += m1.b * m2.c;
				r.d += m1.c * m2.b;
				r.b += m1.a * m2.b + m1.b * m2.d;
				r.c += m1.c * m2.a + m1.d * m2.c;
				r.tx += m1.ty * m2.c;
				r.ty += m1.tx * m2.b;
			}
			return r;
		}
		
		public function toString():String{
			return "TextureSkin: ";
		}
	}
}